//
//  CommonOC.m
//  KeepPwd
//
//  Created by lzh on 2017/11/11.
//  Copyright © 2017年 LZH. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "CommonOC.h"
#import "Common.hpp"
#import <arpa/inet.h>
#import <netdb.h>

@interface CCommonOC ()

@end

@implementation CCommonOC

+ (NSString *)SocketSendAndRead:(NSString *)host port:(NSNumber *)port code:(NSString *)code msg:(NSString *)msg{
    @try{
        // 创建 socket
        int socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0);
        if (-1 == socketFileDescriptor) {
            NSLog(@"创建失败");
            return nil;
        }
        // 获取 IP 地址
        struct hostent * remoteHostEnt = gethostbyname([host UTF8String]);
        if (NULL == remoteHostEnt) {
            close(socketFileDescriptor);
            NSLog(@"%@",@"无法解析服务器的主机名");
            return nil;
        }
        struct in_addr * remoteInAddr = (struct in_addr *)remoteHostEnt->h_addr_list[0];
        // 设置 socket 参数
        struct sockaddr_in socketParameters;
        socketParameters.sin_family = AF_INET;
        socketParameters.sin_addr = *remoteInAddr;
        socketParameters.sin_port = htons([port intValue]);
        // 连接 socket
        int ret = connect(socketFileDescriptor, (struct sockaddr *) &socketParameters, sizeof(socketParameters));
        if (-1 == ret) {
            close(socketFileDescriptor);
            NSLog(@"连接失败");
            return nil;
        }
        NSLog(@"连接成功");
        unsigned char buffer[1024];
        char buffer2[10240];
        
        if(code!=nil&&code!=[NSNull null]){
            buffer[0]=1;
            send(socketFileDescriptor, buffer, 1, 0);
            NSData *testData = [code dataUsingEncoding: NSUTF8StringEncoding];
            unsigned char* x= CCommonB::intToByteArray([testData length]);
            send(socketFileDescriptor, x, 4, 0);
            send(socketFileDescriptor, [testData bytes], [testData length], 0);
        }
        
        NSData *testData = [msg dataUsingEncoding: NSUTF8StringEncoding];
        unsigned char* x= CCommonB::intToByteArray([testData length]);
        send(socketFileDescriptor, x, 4, 0);
        send(socketFileDescriptor, [testData bytes], [testData length], 0);
        
        if(code!=nil&&code!=[NSNull null]){
            recv(socketFileDescriptor, buffer, 1, 0);
            if(buffer[0]==0){
                return @"NoConnected";
            }
        }
        
        recv(socketFileDescriptor, buffer, 4, 0);
        int len=CCommonB::byteArrayToInt(buffer, 0);
        recv(socketFileDescriptor, buffer2, len, 0);
        buffer2[len]='\0';
        NSString *str = [NSString stringWithCString:buffer2 encoding:NSUTF8StringEncoding];
        
        close(socketFileDescriptor);
        
        return str;
        
    }@catch(NSException * e){
        NSLog(@"Exception: %@", e);
        return nil;
    }
}

@end
